Unique Paths II

Follow up for “Unique Paths”:

Now consider if some obstacles are added to the grids. How many unique paths would there be?

An obstacle and empty space is marked as 1 and 0 respectively in the grid.

For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.

  1. [
  2. [0,0,0],
  3. [0,1,0],
  4. [0,0,0]
  5. ]

The total number of unique paths is 2.

Note: m and n will be at most 100.

Solution:

  1. public class Solution {
  2. public int uniquePathsWithObstacles(int[][] obstacleGrid) {
  3. int m = obstacleGrid.length;
  4. int n = obstacleGrid[0].length;
  5. int[][] dp = new int[m][n];
  6. // first row
  7. for (int j = 0; j < n; j++) {
  8. if (obstacleGrid[0][j] == 1) {
  9. break;
  10. }
  11. dp[0][j] = 1;
  12. }
  13. // first col
  14. for (int i = 0; i < m; i++) {
  15. if (obstacleGrid[i][0] == 1) {
  16. break;
  17. }
  18. dp[i][0] = 1;
  19. }
  20. // others
  21. for (int i = 1; i < m; i++) {
  22. for (int j = 1; j < n; j++) {
  23. if (obstacleGrid[i][j] == 0) {
  24. dp[i][j] = dp[i-1][j] + dp[i][j-1];
  25. }
  26. }
  27. }
  28. return dp[m-1][n-1];
  29. }
  30. }